package com.hlm.transparent.core.command;

import com.hlm.transparent.util.ComUtil;
import com.hlm.transparent.util.HexUtil;
import com.hlm.transparent.util.ProtocolHelper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.util.Map;

/**
 * @program:transparent
 * @description:AJ-T188协议命令下发
 * @author: xinY
 **/
public class CJT188Command {

    public static ByteBuf packages(String addr,String protocolCode){
        ByteBuf byteBuf = Unpooled.buffer();
        Map<String,Object> sectionMap = ProtocolHelper.getParameterMap(protocolCode,"command");
        Integer terminalType = ComUtil.safeInt(sectionMap.get("terminaltype"));
        String dataField = ComUtil.safeString(sectionMap.get("datafield"));
        Integer addrOrder = ComUtil.safeInt(sectionMap.get("addrorder"));
        byteBuf.writeByte(0x68);// 起始码
        byteBuf.writeByte(terminalType);// 类型
        byte[] addrBytes = HexUtil.hexStringToByteArray(addr);
        // 顺序
        if (addrOrder == 0){
           for (int i = 0 ; i < addrBytes.length ; i ++ ){
               byteBuf.writeByte(addrBytes[i]);
           }
        }
        // 默认倒叙
        for(int i = addrBytes.length - 1 ; i >= 0 ; i --){
            byteBuf.writeByte(addrBytes[i]);// 表地址
        }

        byteBuf.writeByte(0x01);// 控制码
        byteBuf.writeByte(0x03);// L
        byteBuf.writeBytes(HexUtil.hexStringToByteArray(dataField));
        byteBuf.writeByte(0x12);// 序列号
        int sum = 0;
        for(int i = 0 ; i < byteBuf.readableBytes() ; i ++){
            sum = sum + byteBuf.getByte(i);
        }
        byteBuf.writeByte(sum % 256);// 校验码
        byteBuf.writeByte(0x16);// 结束符
        return byteBuf;
    }
}
